// 用户偏好设置模块
class UserPreferences {
    constructor() {
        this.preferencesContainer = document.getElementById('user-preferences');
        this.defaultPreferences = {
            theme: 'light',
            chartStyle: 'candle',
            refreshRate: 5,
            notifications: true,
            defaultView: 'dashboard',
            riskLevel: 'medium',
            autoSave: true,
            dataDisplayMode: 'table',
            language: 'zh_CN',
            timeZone: 'Asia/Shanghai'
        };

// 使用全局变量导出
window.UserPreferences = UserPreferences;
        
        this.preferences = this.loadPreferences();
        this.initEventListeners();
    }

    // 初始化事件监听器
    initEventListeners() {
        // 保存按钮
        const saveButton = document.getElementById('save-preferences');
        if (saveButton) {
            saveButton.addEventListener('click', () => {
                this.saveAllPreferences();
            });
        }

        // 重置按钮
        const resetButton = document.getElementById('reset-preferences');
        if (resetButton) {
            resetButton.addEventListener('click', () => {
                this.resetPreferences();
            });
        }

        // 主题切换
        const themeSwitch = document.getElementById('theme-switch');
        if (themeSwitch) {
            themeSwitch.addEventListener('change', (e) => {
                this.setPreference('theme', e.target.checked ? 'dark' : 'light');
                this.applyTheme();
            });
        }
    }

    // 渲染偏好设置面板
    renderPreferences() {
        if (!this.preferencesContainer) return;

        const preferencesHTML = `
            <div class="space-y-6">
                <!-- 外观设置 -->
                <div class="bg-white p-4 rounded-lg shadow-sm">
                    <h4 class="text-lg font-medium text-gray-700 mb-4">外观设置</h4>
                    
                    <div class="space-y-4">
                        <!-- 主题设置 -->
                        <div class="flex items-center justify-between">
                            <div>
                                <h5 class="font-medium text-gray-700">深色模式</h5>
                                <p class="text-sm text-gray-500">切换界面为深色主题</p>
                            </div>
                            <label class="switch">
                                <input type="checkbox" id="theme-switch" 
                                    ${this.preferences.theme === 'dark' ? 'checked' : ''}>
                                <span class="slider round"></span>
                            </label>
                        </div>

                        <!-- 图表样式 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">图表样式</h5>
                            <div class="grid grid-cols-3 gap-3">
                                <label class="flex items-center justify-center p-3 border rounded-lg ${
                                    this.preferences.chartStyle === 'candle' ? 'border-blue-500 bg-blue-50' : ''
                                }">
                                    <input type="radio" name="chart-style" value="candle" 
                                        ${this.preferences.chartStyle === 'candle' ? 'checked' : ''}
                                        class="sr-only">
                                    <span>K线图</span>
                                </label>
                                <label class="flex items-center justify-center p-3 border rounded-lg ${
                                    this.preferences.chartStyle === 'line' ? 'border-blue-500 bg-blue-50' : ''
                                }">
                                    <input type="radio" name="chart-style" value="line" 
                                        ${this.preferences.chartStyle === 'line' ? 'checked' : ''}
                                        class="sr-only">
                                    <span>折线图</span>
                                </label>
                                <label class="flex items-center justify-center p-3 border rounded-lg ${
                                    this.preferences.chartStyle === 'area' ? 'border-blue-500 bg-blue-50' : ''
                                }">
                                    <input type="radio" name="chart-style" value="area" 
                                        ${this.preferences.chartStyle === 'area' ? 'checked' : ''}
                                        class="sr-only">
                                    <span>面积图</span>
                                </label>
                            </div>
                        </div>

                        <!-- 数据展示模式 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">数据展示模式</h5>
                            <select id="data-display-mode" class="w-full px-3 py-2 border rounded-lg">
                                <option value="table" ${this.preferences.dataDisplayMode === 'table' ? 'selected' : ''}>表格视图</option>
                                <option value="card" ${this.preferences.dataDisplayMode === 'card' ? 'selected' : ''}>卡片视图</option>
                                <option value="compact" ${this.preferences.dataDisplayMode === 'compact' ? 'selected' : ''}>紧凑视图</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- 通知设置 -->
                <div class="bg-white p-4 rounded-lg shadow-sm">
                    <h4 class="text-lg font-medium text-gray-700 mb-4">通知设置</h4>
                    
                    <div class="space-y-4">
                        <!-- 通知开关 -->
                        <div class="flex items-center justify-between">
                            <div>
                                <h5 class="font-medium text-gray-700">启用通知</h5>
                                <p class="text-sm text-gray-500">接收交易信号和系统通知</p>
                            </div>
                            <label class="switch">
                                <input type="checkbox" id="notifications-switch" 
                                    ${this.preferences.notifications ? 'checked' : ''}>
                                <span class="slider round"></span>
                            </label>
                        </div>

                        <!-- 刷新频率 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">数据刷新频率(秒)</h5>
                            <input type="range" id="refresh-rate" min="1" max="30" step="1" 
                                value="${this.preferences.refreshRate}"
                                class="w-full">
                            <div class="flex justify-between text-sm text-gray-500 mt-1">
                                <span>1秒</span>
                                <span id="refresh-rate-value">${this.preferences.refreshRate}秒</span>
                                <span>30秒</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 交易设置 -->
                <div class="bg-white p-4 rounded-lg shadow-sm">
                    <h4 class="text-lg font-medium text-gray-700 mb-4">交易设置</h4>
                    
                    <div class="space-y-4">
                        <!-- 默认视图 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">默认视图</h5>
                            <select id="default-view" class="w-full px-3 py-2 border rounded-lg">
                                <option value="dashboard" ${this.preferences.defaultView === 'dashboard' ? 'selected' : ''}>仪表盘</option>
                                <option value="minute-trading" ${this.preferences.defaultView === 'minute-trading' ? 'selected' : ''}>分钟交易</option>
                                <option value="selector" ${this.preferences.defaultView === 'selector' ? 'selected' : ''}>股票选择器</option>
                                <option value="training" ${this.preferences.defaultView === 'training' ? 'selected' : ''}>模型训练</option>
                            </select>
                        </div>

                        <!-- 风险等级 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">风险等级</h5>
                            <div class="grid grid-cols-3 gap-3">
                                <label class="flex items-center justify-center p-3 border rounded-lg ${
                                    this.preferences.riskLevel === 'low' ? 'border-blue-500 bg-blue-50' : ''
                                }">
                                    <input type="radio" name="risk-level" value="low" 
                                        ${this.preferences.riskLevel === 'low' ? 'checked' : ''}
                                        class="sr-only">
                                    <span>低风险</span>
                                </label>
                                <label class="flex items-center justify-center p-3 border rounded-lg ${
                                    this.preferences.riskLevel === 'medium' ? 'border-blue-500 bg-blue-50' : ''
                                }">
                                    <input type="radio" name="risk-level" value="medium" 
                                        ${this.preferences.riskLevel === 'medium' ? 'checked' : ''}
                                        class="sr-only">
                                    <span>中等风险</span>
                                </label>
                                <label class="flex items-center justify-center p-3 border rounded-lg ${
                                    this.preferences.riskLevel === 'high' ? 'border-blue-500 bg-blue-50' : ''
                                }">
                                    <input type="radio" name="risk-level" value="high" 
                                        ${this.preferences.riskLevel === 'high' ? 'checked' : ''}
                                        class="sr-only">
                                    <span>高风险</span>
                                </label>
                            </div>
                        </div>

                        <!-- 自动保存 -->
                        <div class="flex items-center justify-between">
                            <div>
                                <h5 class="font-medium text-gray-700">自动保存设置</h5>
                                <p class="text-sm text-gray-500">自动保存交易记录和偏好设置</p>
                            </div>
                            <label class="switch">
                                <input type="checkbox" id="auto-save-switch" 
                                    ${this.preferences.autoSave ? 'checked' : ''}>
                                <span class="slider round"></span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- 区域设置 -->
                <div class="bg-white p-4 rounded-lg shadow-sm">
                    <h4 class="text-lg font-medium text-gray-700 mb-4">区域设置</h4>
                    
                    <div class="space-y-4">
                        <!-- 语言 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">语言</h5>
                            <select id="language" class="w-full px-3 py-2 border rounded-lg">
                                <option value="zh_CN" ${this.preferences.language === 'zh_CN' ? 'selected' : ''}>简体中文</option>
                                <option value="en_US" ${this.preferences.language === 'en_US' ? 'selected' : ''}>English (US)</option>
                                <option value="zh_TW" ${this.preferences.language === 'zh_TW' ? 'selected' : ''}>繁體中文</option>
                            </select>
                        </div>

                        <!-- 时区 -->
                        <div>
                            <h5 class="font-medium text-gray-700 mb-2">时区</h5>
                            <select id="timezone" class="w-full px-3 py-2 border rounded-lg">
                                <option value="Asia/Shanghai" ${this.preferences.timeZone === 'Asia/Shanghai' ? 'selected' : ''}>中国标准时间 (UTC+8)</option>
                                <option value="America/New_York" ${this.preferences.timeZone === 'America/New_York' ? 'selected' : ''}>美国东部时间</option>
                                <option value="Europe/London" ${this.preferences.timeZone === 'Europe/London' ? 'selected' : ''}>英国标准时间</option>
                                <option value="Asia/Tokyo" ${this.preferences.timeZone === 'Asia/Tokyo' ? 'selected' : ''}>日本标准时间</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="flex justify-end space-x-3">
                    <button id="reset-preferences" class="btn-secondary">
                        恢复默认设置
                    </button>
                    <button id="save-preferences" class="btn-primary">
                        保存设置
                    </button>
                </div>
            </div>
        `;

        this.preferencesContainer.innerHTML = preferencesHTML;
        this.initEventListeners();

        // 添加刷新频率滑块值显示
        const refreshRateSlider = document.getElementById('refresh-rate');
        const refreshRateValue = document.getElementById('refresh-rate-value');
        if (refreshRateSlider && refreshRateValue) {
            refreshRateSlider.addEventListener('input', (e) => {
                refreshRateValue.textContent = `${e.target.value}秒`;
            });
        }

        // 添加单选按钮样式切换
        document.querySelectorAll('input[type="radio"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                // 清除同组单选按钮的选中样式
                const name = e.target.name;
                document.querySelectorAll(`input[name="${name}"]`).forEach(r => {
                    r.closest('label').classList.remove('border-blue-500', 'bg-blue-50');
                });
                
                // 添加当前选中单选按钮的样式
                e.target.closest('label').classList.add('border-blue-500', 'bg-blue-50');
                
                // 更新偏好设置
                if (name === 'chart-style') {
                    this.setPreference('chartStyle', e.target.value);
                } else if (name === 'risk-level') {
                    this.setPreference('riskLevel', e.target.value);
                }
            });
        });

        // 添加下拉框事件监听
        document.getElementById('data-display-mode')?.addEventListener('change', (e) => {
            this.setPreference('dataDisplayMode', e.target.value);
        });

        document.getElementById('default-view')?.addEventListener('change', (e) => {
            this.setPreference('defaultView', e.target.value);
        });

        document.getElementById('language')?.addEventListener('change', (e) => {
            this.setPreference('language', e.target.value);
        });

        document.getElementById('timezone')?.addEventListener('change', (e) => {
            this.setPreference('timeZone', e.target.value);
        });

        // 添加开关事件监听
        document.getElementById('notifications-switch')?.addEventListener('change', (e) => {
            this.setPreference('notifications', e.target.checked);
        });

        document.getElementById('auto-save-switch')?.addEventListener('change', (e) => {
            this.setPreference('autoSave', e.target.checked);
        });
    }

    // 加载偏好设置
    loadPreferences() {
        const savedPreferences = localStorage.getItem('userPreferences');
        return savedPreferences ? JSON.parse(savedPreferences) : this.defaultPreferences;
    }

    // 保存单个偏好设置
    setPreference(key, value) {
        this.preferences[key] = value;
        if (this.preferences.autoSave) {
            this.savePreferences();
        }
    }

    // 保存所有偏好设置
    saveAllPreferences() {
        // 收集所有表单值
        const chartStyle = document.querySelector('input[name="chart-style"]:checked')?.value || this.preferences.chartStyle;
        const riskLevel = document.querySelector('input[name="risk-level"]:checked')?.value || this.preferences.riskLevel;
        const dataDisplayMode = document.getElementById('data-display-mode')?.value || this.preferences.dataDisplayMode;
        const defaultView = document.getElementById('default-view')?.value || this.preferences.defaultView;
        const language = document.getElementById('language')?.value || this.preferences.language;
        const timeZone = document.getElementById('timezone')?.value || this.preferences.timeZone;
        const refreshRate = document.getElementById('refresh-rate')?.value || this.preferences.refreshRate;
        const theme = document.getElementById('theme-switch')?.checked ? 'dark' : 'light';
        const notifications = document.getElementById('notifications-switch')?.checked || this.preferences.notifications;
        const autoSave = document.getElementById('auto-save-switch')?.checked || this.preferences.autoSave;

        // 更新偏好设置对象
        this.preferences = {
            ...this.preferences,
            chartStyle,
            riskLevel,
            dataDisplayMode,
            defaultView,
            language,
            timeZone,
            refreshRate,
            theme,
            notifications,
            autoSave
        };

        // 保存到本地存储
        this.savePreferences();
        
        // 显示保存成功提示
        this.showToast('设置已保存');
    }

    // 保存偏好设置到本地存储
    savePreferences() {
        localStorage.setItem('userPreferences', JSON.stringify(this.preferences));
    }

    // 重置偏好设置
    resetPreferences() {
        this.preferences = { ...this.defaultPreferences };
        this.savePreferences();
        this.renderPreferences();
        this.applyTheme();
        this.showToast('已恢复默认设置');
    }

    // 应用主题
    applyTheme() {
        document.documentElement.classList.toggle('dark-mode', this.preferences.theme === 'dark');
    }

    // 显示提示消息
    showToast(message) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = 'fixed bottom-4 right-4 bg-gray-800 text-white px-4 py-2 rounded-lg shadow-lg z-50';
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 2秒后移除
        setTimeout(() => {
            toast.classList.add('opacity-0', 'transition-opacity', 'duration-500');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 500);
        }, 2000);
    }
}